//package shiyan3;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class shiyan3_1 {
    public static final String key = "jkl;POIU1234++==";
    public static final byte[] rand = {1,2,3,4,5,6,7,8,9,0,11,12,12,14,15,16};
    public static void main(String[] args) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(rand);
        //String[] args = {"DEC","shiyan","deshiyan"};
        if(args.length!=3){
            System.out.println("请输入三个参数");
            return;
        }
        if(args[0].equals("ENC")){encryptFile(args[1],args[2],key,iv);
        }
        else if(args[0].equals("DEC")){
            decryptFile(args[1],args[2],key,iv);
        }
    }

    //文件加密
    public static void encryptFile(String infile,String outfile,String key,IvParameterSpec iv) throws Exception {
        FileInputStream finput = new FileInputStream(infile);
        int num = finput.available();
        byte[] indata = new byte[num];
        finput.read(indata);
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skey = new SecretKeySpec(raw,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,skey,iv);
        byte[] encdata = cipher.doFinal(indata);
        FileOutputStream fOutput = new FileOutputStream(outfile);
        fOutput.write(encdata);
        finput.close();
        fOutput.close();
    }
    public static void decryptFile(String infile,String outfile,String key,IvParameterSpec iv) throws Exception {
        FileInputStream fInput = new FileInputStream(infile);
        int num = fInput.available();
        byte[] indata = new byte[num];
        fInput.read(indata);
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec skey = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skey,iv);
        byte[] encdata = cipher.doFinal(indata);
        FileOutputStream fOutput = new FileOutputStream(outfile);
        fOutput.write(encdata);
        fInput.close();
        fOutput.close();
    }
}
